<template>
  <el-container style="display: flex; justify-content: center; height: 100%">
    <el-card class="box-card">
      <el-form :model="searchForm" inline class="search-form">
        <el-row :gutter="20" type="flex" justify="space-between" align="middle">
          <el-col :span="16">
            <el-form-item label="队伍" style="width: 200px;">
              <el-select v-model="searchForm.year" placeholder="请选择">
                <el-option value="">全部</el-option>
                <el-option v-for="item in Team" :key="item.di" :label="item.teamName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-input v-model="searchQuery" placeholder="输入身份证号" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary">
                查询
              </el-button>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="text-right">
              <el-input v-model="revisestaff" placeholder="请输入操作人员的序号"></el-input>
              <el-button type="success" @click="addEvents">
                操作人员
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="filteredData" border style="width: 100%">
        <el-table-column prop="id" label="序号" width="70" />
        <el-table-column prop="userName" label="姓名" width="110" />
        <el-table-column prop="sex" label="性别" width="90" />
        <el-table-column prop="role" label="身份" width="130" />
        <el-table-column label="队伍" width="190">
          <template #default="{ row }">
            <span>{{ rowteamName(row.teamGroupId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="组别" width="160">
          <template #default="{ row }">
            <span>{{ rowgroupName(row.matchesGroupId) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="idcard" label="身份证号" width="230" />
        <el-table-column prop="phone" label="联系电话" width="190" />
        <el-table-column prop="email" label="邮箱" width="210" />
        <el-table-column prop="birthday" label="出生日期" width="160" />
        <el-table-column prop="image" label="照片" >
          <template #default="{ row }">
            <img :src="serverUrl + row.image" alt="" style="width: 50px; height: 50px; object-fit: cover;" />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </el-container>
  <el-dialog title="操作人员" v-model="dialogVisible" width="30%" @close="dialogVisible = false">
    <el-form :model="editForm">
      <el-form-item label="姓名">
        <el-input v-model="editForm.userName" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="身份证号">
        <el-input v-model="editForm.idcard" placeholder="请输入身份证号"></el-input>
      </el-form-item>
      <el-form-item label="出生年月">
        <el-input v-model="editForm.birthday" placeholder="请输入出生年月"></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-input v-model="editForm.sex" placeholder="请输入性别"></el-input>
      </el-form-item>
      <el-form-item label="手机号码">
        <el-input v-model="editForm.phone" placeholder="请输入手机号码"></el-input>
      </el-form-item>
      <el-form-item label="参赛组别">
        <el-select v-model="editForm.matchesGroupId" placeholder="请选择参赛组别">
          <el-option v-for="group in group" :key="group.id" :label="group.groupname" :value="group.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="照片">
        <el-upload class="avatar-uploader" action="http://back1.idcfengye.com:15173/competition/upload" :show-file-list="false"
          :http-request="customUpload" :before-upload="beforeUpload">
          <img v-if="editForm.image" :src="serverUrl + editForm.image" class="avatar" style="width: 150px;">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          <el-button link icon="el-icon-delete" @click="deletePhoto" v-if="editForm.image">删除照片</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <span class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitEdit">提交修改</el-button>
      <el-button type="primary" @click="handleSubmit">删除人员</el-button>
    </span>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';

const noimage = ref('');
const token = localStorage.getItem('adminToken');
const editForm = ref([]);
const searchForm = ref({});
const searchQuery = ref('');
const tableData = ref([]);
const Team = ref([]);
const group = ref([]);
const revisestaff = ref('');
const dialogVisible = ref(false);

const serverUrl = ref('http://back1.idcfengye.com:15173');

// 获取所有人员的信息
async function fetchstaff() {
  try {
    const response = await axios.get('http://back1.idcfengye.com:15173/api/getAllStaff', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    tableData.value = response.data.data; // 确保后端返回的数据结构与此匹配
  } catch (error) {
    console.log(error);
  }
}

// 获取所有比赛的团队信息
async function fetchTeamData() {
  try {
    const response = await axios.get('http://back1.idcfengye.com:15173/api/getAllTeam', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    Team.value = response.data.data; // 确保后端返回的数据结构与此匹配
  } catch (error) {
    console.log(error);
  }
}

// 获取所有比赛的组别信息
async function fetchgroupData() {
  try {
    const response = await axios.get('http://back1.idcfengye.com:15173/competition/group/admin', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    group.value = response.data.data; // 确保后端返回的数据结构与此匹配
  } catch (error) {
    console.log(error);
  }
}

onMounted(() => {
  fetchstaff();
  fetchTeamData();
  fetchgroupData();
});

// 根据组别id获取队伍名称
function rowteamName(id) {
  const teamName = Team.value.find(item => item.id === id)
  return teamName ? teamName.teamName : '未分配';
}

// 根据组别id获取组别名称
function rowgroupName(id) {
  const groupName = group.value.find(item => item.id === id)
  return groupName ? groupName.groupname : '未分配';
}

// 计算属性：根据 searchQuery 和 searchForm.year 来过滤数据
const filteredData = computed(() => {
  return tableData.value.filter(item => {
    const teamMatch = searchForm.value.year ? item.teamGroupId === searchForm.value.year : true;
    const idcardMatch = searchQuery.value ? item.idcard.includes(searchQuery.value) : true;
    return teamMatch && idcardMatch;
  });
});

//操作人员
function addEvents() {
  if (revisestaff.value === '') {
    ElMessage.error('请选择要操作的人员的序号');
    return;
  }

  // 将 revisestaff.value 转换为数字
  const index = parseInt(revisestaff.value);

  // 使用 find 方法查找对应的人员信息
  const table = tableData.value.find(item => item.id === index);

  if (!table) {
    ElMessage.error('未找到对应的人员信息');
    return;
  }

  editForm.value = table; // 将找到的人员信息赋值给 editForm
  dialogVisible.value = true; // 显示对话框
}

// 自定义上传方法
const customUpload = async (file) => {
  const formData = new FormData();
  formData.append('file', file.file);

  try {
    const response = await axios.post('http://back1.idcfengye.com:15173/competition/upload', formData, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'multipart/form-data'
      }
    });
    if (response.data.success) {
      editForm.value.image = response.data.path;
      ElMessage.success('图片上传成功');
    } else {
      ElMessage.error('图片上传失败');
    }
  } catch (error) {
    console.error(error);
    ElMessage.error('图片上传失败');
  }
};

// 上传前的检查
const beforeUpload = (file) => {
  // 可以在这里添加文件类型和大小的检查
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('只能上传图片文件');
    return false;
  }
  // 可以添加文件大小的检查
  return isImage;
};

// 删除 '/upload/' 的函数
function removeUploadPath(filePath) {
  return filePath.replace('/upload/', '');
}

// 删除照片的方法
const deletePhoto = async () => {
  noimage.value = editForm.value.image;
  const cleanedImagePath = removeUploadPath(noimage.value);
  
  try {
    // 调用后端接口删除服务器上的照片
    await axios.delete(`http://back1.idcfengye.com:15173/competition/delete/${cleanedImagePath}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    // 从 editForm 中移除照片 URL
    editForm.value.image = '';
    ElMessage.success('照片删除成功');
  } catch (error) {
    console.error(error);
    if (error.code === 'ERR_NETWORK') {
      ElMessage.error('网络请求失败，请检查你的网络连接或服务器状态。');
    } else {
      ElMessage.error('删除失败：' + error.message);
    }
  }
}

// 修改的方法
async function submitEdit() {
  const id = editForm.value.id;
  try {
    const response = await axios.put(`http://back1.idcfengye.com:15173/competition/teamstaff/staff/${id}`, editForm.value, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    if (response.data.success) {
      ElMessage.success('修改成功');
      revisestaff.value = ''
      editForm.value = {}
      fetchstaff();
      fetchTeamData();
      fetchgroupData();
      dialogVisible.value = false
    }
  } catch (error) {
    if (error.response && error.response.data) {
      ElMessage.error(error.response.data.message || '修改失败');
    }
  }
}

// 删除的方法
async function deleteStaff() {
  const id = editForm.value.id;
  try {
    const response = await axios.delete(`http://back1.idcfengye.com:15173/competition/teamstaff/staff/${id}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    if (response.data.success) {
      ElMessage.success('删除成功');
      revisestaff.value = ''
      editForm.value = {}
      fetchstaff();
      fetchTeamData();
      fetchgroupData();
      dialogVisible.value = false
    }
  } catch (error) {
    if (error.response && error.response.data) {
      ElMessage.error(error.response.data.message || '删除失败');
    }
  }
}

// 删除团队再确认
const handleSubmit = async () => {
  ElMessageBox.confirm(`您确定要删除`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteStaff();
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除'
    });
  });
};
</script>

<style scoped>
.avatar-uploader-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 150px; /* 与图片宽度一致 */
  height: 150px; /* 与图片高度一致 */
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  font-size: 2rem;
  color: #999;
}

.avatar-uploader-icon:hover {
  border-color: #409EFF;
  color: #409EFF;
}
</style>